package com.hup.sidebar.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.hup.sidebar.R;
import com.hup.sidebar.constant.PieFunctionConstant;
import com.hup.sidebar.framework.view.BaseAdapter;
import com.hup.sidebar.framework.view.BaseViewHolder;
import com.hup.sidebar.model.PieFunction;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 选择单个(短按/长按)功能的界面
 *
 * @author hugan
 * @date 2022/6/6
 */
@SuppressLint("NonConstantResourceId")
public class SelectFunctionActivity extends AppCompatActivity implements OnItemClickListener {
    private static final String TAG = SelectFunctionActivity.class.getSimpleName();
    public static final int REQUEST_CODE = 13865;

    @BindView(R.id.listView)
    ListView listView;

    private PieFunctionAdapter adapter;

    /**
     * startActivityForResult时的入参,不使用Bundle传递
     * 是入参对象的copy
     */
    private static PieFunction requestFunction;
    /**
     * 入参是TYPE_APP时的app名,nullable
     */
    private static String requestAppName;
    /**
     * startActivityForResult返回时的结果,不使用Bundle传递
     */
    private static PieFunction resultFunction;

    /**
     * @param pieFunction 已选择的功能,nullable
     */
    public static void startActivityForResult(Activity context, PieFunction pieFunction) {
        Log.i(TAG, "startActivityForResult: " + pieFunction);
        requestFunction = pieFunction == null ? PieFunctionConstant.getNone(context) : pieFunction.copy();
        if (requestFunction.type == PieFunctionConstant.TYPE_APP && requestFunction.command != null) {
            try {
                //获取app名
                PackageManager packageManager = context.getPackageManager();
                ApplicationInfo info = packageManager.getApplicationInfo(requestFunction.command, 0);
                requestAppName = packageManager.getApplicationLabel(info).toString();
            } catch (NameNotFoundException e) {
                Log.e(TAG, "startActivityForResult: ", e);
                requestAppName = requestFunction.command;
            }
        }
        resultFunction = null;
        Intent intent = new Intent(context, SelectFunctionActivity.class);
        context.startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.select_function_activity);
        ButterKnife.bind(this);

        ArrayList<PieFunction> functions = PieFunctionConstant.functions(this);
        adapter = new PieFunctionAdapter();
        adapter.setData(functions);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PieFunction function = adapter.getItem(position);
        if (function.type == PieFunctionConstant.TYPE_APP) {
            //打开app选择界面
            String packageName = null;
            if (requestFunction.type == PieFunctionConstant.TYPE_APP && requestFunction.command != null) {
                //传递本类的入参
                packageName = requestFunction.command;
            }
            SelectAppActivity.startActivityForResult(this, packageName);
            /*
            启动界面后,马上关闭本界面, 但也要设置RESULT_OK,
            因为跨了两个activity, 导致上层activity的onActivityResult总不能获取到 SelectAppActivity.RESULT_OK/CANCELED
             */
        }
        resultFunction = function;
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void finish() {
        Log.i(TAG, "finish: ");
        super.finish();
        requestFunction = null;
        requestAppName = null;
    }

    /**
     * 处理本类的返回结果
     *
     * @param requestCode 需要等于 {@link SelectFunctionActivity#REQUEST_CODE}
     * @return null-直接返回/取消选择,notNull-RESULT_OK时返回的数据,与SelectFunctionActivity.context内存无关的,能直接在全局使用的
     */
    public static PieFunction handleActivityResult(Context context, int requestCode, int resultCode) {
        if (requestCode != REQUEST_CODE) throw new IllegalArgumentException("代码异常");
        if (resultCode != RESULT_OK) return null;
        if (resultFunction == null) throw new IllegalArgumentException("代码异常");

        Log.i(TAG, "handleActivityResult: " + resultFunction);
        PieFunction res = resultFunction.copy();//返回copy,确保res和SelectFunctionActivity.context无关
        resultFunction = null;//释放内存

        if (res.type == PieFunctionConstant.TYPE_APP) {
            //从SelectAppActivity返回
            res.command = SelectAppActivity.getResultPackage();
            SelectAppActivity.afterHandleActivityResult();
            if (res.command == null) return null;//command为空代表SelectAppActivity取消选择,则返回null
        }
        return res;
    }

    private static class PieFunctionAdapter extends BaseAdapter<PieFunction, PieFunctionViewHolder> {
        @Override
        public int getLayoutResId() {
            return R.layout.select_function_item;
        }

        @Override
        public PieFunctionViewHolder createHolder() {
            return new PieFunctionViewHolder();
        }
    }

    public static class PieFunctionViewHolder implements BaseViewHolder<PieFunction> {
        @BindView(R.id.imgIcon)
        ImageView imgIcon;
        @BindView(R.id.txtDesc)
        TextView txtDesc;
        @BindView(R.id.txtDesc2)
        TextView txtDesc2;
        @BindView(R.id.imgCheck)
        ImageView imgCheck;

        @Override
        public void onBindView(View view) {
        }

        @Override
        public void bindData(int position, PieFunction item) {
            //Log.i(TAG, "bindData: " + position + ", item=" + item + ", req=" + requestFunction);
            if (requestFunction == null) return;//打开SelectAppActivity且finish后,到达此处!

            /*
            下面的drawable,都由当前界面 SelectFunctionActivity.context创建的
            不使用PieFunction.cachedIcon, SelectFunctionActivity关闭后,会释放drawable内存
             */
            if (item.type == PieFunctionConstant.TYPE_APP && requestFunction.type == PieFunctionConstant.TYPE_APP) {
                //item和requestFunction都是 TYPE_APP时
                txtDesc.setText(R.string.func_app);
                if (requestFunction.command == null) {
                    txtDesc2.setText(R.string.select_function_select_none);
                    imgIcon.setImageResource(R.drawable.func_app);
                } else {
                    txtDesc2.setText(requestAppName);
                    imgIcon.setImageDrawable(PieFunctionConstant.getIcon(imgCheck.getContext(), requestFunction));
                }
                txtDesc2.setVisibility(View.VISIBLE);
                imgCheck.setVisibility(View.VISIBLE);
            } else {
                boolean selected = requestFunction.isSame(item);
                txtDesc.setText(item.command);
                txtDesc2.setVisibility(View.GONE);
                imgCheck.setVisibility(selected ? View.VISIBLE : View.INVISIBLE);
                if (PieFunctionConstant.TYPE_APP == item.type) {
                    imgIcon.setImageResource(R.drawable.func_app);
                } else {
                    imgIcon.setImageDrawable(PieFunctionConstant.getIcon(imgCheck.getContext(), item));
                }
            }
        }
    }

}
